package com.nation.controller;

import com.nation.domain.*;
import com.nation.service.ContinentService;
import com.nation.service.NationInfoService;
import com.nation.service.NatureService;
import com.nation.service.PopulationService;
import com.nation.serviceImpl.NaitonInfoServiceImpl;
import com.nation.utils.HandelExcel;
import com.nation.utils.HandleZIP;
import com.nation.utils.JSON;
import com.nation.utils.ReadAndStoreFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.protocol.HTTP;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.print.attribute.standard.MediaSize;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqd on 2017/11/1.
 */
@Controller
@RequestMapping(value = "/BaseInformation")
public class BaseInformationController {

    @Autowired
    ContinentService ContinentService;

    @Autowired
    NationInfoService NationInfoService;

    @Autowired
    PopulationService PopulationService;


    /**
     * 转到国家基本信息
     * @param map 存传到前端的数据
     * @return
     */
    @RequestMapping(value = "/baseinfo")
    public String baseinfo(ModelMap map){
        List<TContinentC> clist= ContinentService.findAllContinent();
        List<TNationInfo> nlist= NationInfoService.findAllNationInfo();
        System.out.println(clist.get(0).getContinent_id()+"---+++");
        map.put("clist",clist);
        map.put("nlist",nlist);
        return "BaseInformation/baseinfo";
    }

    /**
     * 基本信息条件查询
     * @param request 获取前端传回的数据
     * @param mmap 将数据传到前端
     * @return
     */
    @RequestMapping(value = "/InfoSearch")
    public String InfoSearch(HttpServletRequest request,ModelMap mmap){
        String nation_z=request.getParameter("nation_z");
        String nation_e=request.getParameter("nation_e");
        String continent=request.getParameter("continent");
        String recoder_id=request.getParameter("recoder_id");
        Map<String,Object> map=new HashMap<String,Object>();
        System.out.println(nation_z+"nation_z---");
        map.put("nation_z",nation_z);
        map.put("nation_e",nation_e);
        map.put("continent",continent);
        map.put("recoder_id",recoder_id);
        List<TNationInfo> nlist=NationInfoService.findByCondition(map);
        List<TContinentC> clist= ContinentService.findAllContinent();
        mmap.put("clist",clist);
        mmap.put("nlist",nlist);
        return "BaseInformation/baseinfo";
    }

    /**
     * 查看详情国家信息
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/nationinfo_detail")
    public String nationinfo_detail(HttpServletRequest request,ModelMap map){
        String country_code=request.getParameter("country_code");
        TNationInfo nationinfo=NationInfoService.findByCountryCode(country_code);
        map.put("nationinfo",nationinfo);
        return "BaseInformation/baseinfo-detail";
    }

    /**
     * 跳转到修改页面
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/nationinfo_update")
    public String nationinfo_update(HttpServletRequest request,ModelMap map){
        String country_code=request.getParameter("country_code");
        TNationInfo nationinfo=NationInfoService.findByCountryCode(country_code);
        List<TContinentC> clist= ContinentService.findAllContinent();
        map.put("clist",clist);
        map.put("nationinfo",nationinfo);
        System.out.println(nationinfo.getCountry_code()+"code");
        return "BaseInformation/baseinfo-update";
    }

    /**
     * 修改基本信息
     * @param
     * @return
     */
    @RequestMapping(value = "/nationinfo_update.do")
    @ResponseBody
    public String nationinfo_update_do(HttpServletRequest request){
        String establish_time=request.getParameter("establish_time");
        String  capital_longitude=request.getParameter("capital_longitude");
        String  capital_latitude=request.getParameter("capital_latitude");;
        String  country_area=request.getParameter("country_area");;
        String  capital=request.getParameter("capital");;
        String  administrative_division=request.getParameter("administrative_division");;
        String  continent=request.getParameter("continent");;
        String country_code=request.getParameter("country_code");
        Double clo=Double.parseDouble(capital_longitude);
        Double cla=Double.parseDouble(capital_latitude);
        Double ca=Double.parseDouble(country_area);
        TNationInfo nationInfo=new TNationInfo();
        nationInfo.setAdministrative_division(administrative_division);
        nationInfo.setCapital(capital);
        nationInfo.setCapital_latitude(cla);
        nationInfo.setCapital_longitude(clo);
        nationInfo.setContinent(continent);
        nationInfo.setCountry_area(ca);
        nationInfo.setCountry_code(country_code);
        nationInfo.setEstablish_time(establish_time);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        nationInfo.setRecoder_time(sdf.format(System.currentTimeMillis()));
        Boolean judge=NationInfoService.updateNationInfo(nationInfo);
        if(judge)
            return "修改成功";
        else
            return "修改失败";
    }

    /*
    * 上传国家的相关excel或者压缩包文件
    * @param*/
    @RequestMapping(value = "/uploadNationFile.do")
    @ResponseBody
    public String uploadNationFile(HttpServletRequest request, MultipartFile nation_file,@RequestParam(value = "selectFileKind")int selectFileKind){
        List<String> picture_paths=new ArrayList<String>();
        org.apache.shiro.subject.Subject currentuser= SecurityUtils.getSubject();
        User user=(User)currentuser.getPrincipal();
        String input_code=user.getYHZH();

        if (selectFileKind==0){ //如果是国家的表格
            try {
                String path=request.getSession().getServletContext().getResource("/").getPath();
                path += ReadAndStoreFile.EXCELTEMP;
                String file_path=ReadAndStoreFile.save(nation_file,path);

                HandelExcel poi = new HandelExcel();
                List<List<String>> list = poi.read(file_path);

                NationInfoService.uploadNationMessage(list,input_code);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
            return "上传成功";
        }else{
            try{
                String path=request.getSession().getServletContext().getResource("/").getPath();
                String picture_path=null;
                String folder="";
                switch(selectFileKind){
                    case 1: picture_path=path+ HandleZIP.LOCATIONMAPS;folder=HandleZIP.LOCATIONMAPS;break;//区位地图
                    case 2: picture_path=path+ HandleZIP.NATIONALEMBLEMS;folder=HandleZIP.NATIONALEMBLEMS;break;//国徽
                    case 3: picture_path=path+ HandleZIP.NATIONALFLAGS;folder=HandleZIP.NATIONALFLAGS;break;//国旗
                    case 4: picture_path=path+ HandleZIP.NATIONALSONGS;folder=HandleZIP.NATIONALSONGS;break;//国歌
                }

                System.out.println("path--"+picture_path);

//          将MultipartFile格式转换成File
                CommonsMultipartFile cf= (CommonsMultipartFile)nation_file; //这个picture_ZIP是MultipartFile的
                DiskFileItem fi = (DiskFileItem)cf.getFileItem();
                File file = fi.getStoreLocation();
                picture_paths=HandleZIP.unzip( file,picture_path,folder);

            }catch (IOException e){
                e.printStackTrace();
                return "上传失败";
            }finally {
                NationInfoService.uploadNationFile(picture_paths,input_code,selectFileKind);
            }
            return "上传成功";
        }


    }
    @RequestMapping(value = "/nationinfo_add")
    public String nationinfo_add(ModelMap map){
        List<TContinentC> clist= ContinentService.findAllContinent();
        map.put("clist",clist);
        return "BaseInformation/baseinfo-add";
    }
    @RequestMapping(value = "/nationinfo_add.do")
    @ResponseBody
    public String nationinfo_add_do(HttpServletRequest request){
        String name=request.getParameter("name_z");
        String name_e=request.getParameter("name_e");
        String establish_time=request.getParameter("establish_time");
        String  capital_longitude=request.getParameter("capital_longitude");
        String  capital_latitude=request.getParameter("capital_latitude");;
        String  country_area=request.getParameter("country_area");;
        String  capital=request.getParameter("capital");;
        String  administrative_division=request.getParameter("administrative_division");;
        String  continent=request.getParameter("continent");;
        //String country_code=request.getParameter("country_code");
        Double clo=0.0,cla=0.0,ca=0.0;
        if(capital_longitude!=null && capital_longitude!="")
            clo=Double.parseDouble(capital_longitude);
        if(capital_latitude!=null && capital_latitude!="")
            cla=Double.parseDouble(capital_latitude);
        if(country_area!=null && country_area!="")
            ca=Double.parseDouble(country_area);
        TNationInfo nationInfo=new TNationInfo();
        nationInfo.setAdministrative_division(administrative_division);
        nationInfo.setCapital(capital);
        nationInfo.setCapital_latitude(cla);
        nationInfo.setCapital_longitude(clo);
        nationInfo.setContinent(continent);
        nationInfo.setCountry_area(ca);
        //nationInfo.setCountry_code(country_code);
        System.out.println(name+"---");
        if(establish_time!=null && establish_time!="")
        nationInfo.setEstablish_time(establish_time);
        TCountry tc= NationInfoService.findCountryByName(name);
        nationInfo.setCountry_code(continent+tc.getCountry_code());
        nationInfo.setNation_e(name_e);
        nationInfo.setNation_z(name);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        nationInfo.setRecoder_id(user.getYHZH());
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        nationInfo.setRecoder_time(sdf.format(System.currentTimeMillis()));
        Boolean judge=NationInfoService.insertNationInfo(nationInfo);
        if(judge)
            return "添加成功";
        else
            return "添加失败";
    }
    @RequestMapping(value = "/upload_statistics")
    public String upload_statistics(ModelMap map, HttpServletRequest request){
        String country_code=request.getParameter("country_code");
        map.put("country_code",country_code);
        return "BaseInformation/upload-statistics";
    }
    @RequestMapping(value = "/uploadStatistics.do")
    @ResponseBody
    public String uploadStatistics_do(MultipartFile file,String country_code) throws IOException, InvalidFormatException {
        /*Workbook wb=WorkbookFactory.create(file.getInputStream());
        Sheet sheet=wb.getSheetAt(0);
        int last=sheet.getLastRowNum();
        String name=file.getOriginalFilename();
        if(name.substring(4,name.length()-4).equals("人口")){
            TPopulation population=new TPopulation();System.out.println(name.substring(4,name.length()-4)+"-=");
            String sourceData=sheet.getRow(0).getCell(0).getStringCellValue();
            population.setSource_database(sourceData.substring(4,sourceData.length()));
            population.setYear(name.substring(0,4));
            population.setCountry_code(country_code);
            population.setContinent(country_code.substring(0,1));
            population.setMid_year_population(sheet.getRow(3).getCell(1).getNumericCellValue());
            population.setPopulation_rate_0(sheet.getRow(4).getCell(1).getNumericCellValue());
            population.setPopulation_rate_15(sheet.getRow(5).getCell(1).getNumericCellValue());
            population.setPopulation_rate_65(sheet.getRow(6).getCell(1).getNumericCellValue());
            population.setFemale_rate(sheet.getRow(7).getCell(1).getNumericCellValue());
            population.setIncrease_rate(sheet.getRow(8).getCell(1).getNumericCellValue());
            population.setDensity(sheet.getRow(9).getCell(1).getNumericCellValue());
            population.setBirth_rate(sheet.getRow(10).getCell(1).getNumericCellValue());
            population.setAve_life(sheet.getRow(11).getCell(1).getNumericCellValue());
            population.setTotal_birth_rate(sheet.getRow(12).getCell(1).getNumericCellValue());
            population.setDeath_rate(sheet.getRow(13).getCell(1).getNumericCellValue());
            population.setBaby_death_rate(sheet.getRow(14).getCell(1).getNumericCellValue());
            population.setDependency_rate(sheet.getRow(15).getCell(1).getNumericCellValue());
            population.setCity_population(sheet.getRow(16).getCell(1).getNumericCellValue());
            population.setCity_population_rate(sheet.getRow(17).getCell(1).getNumericCellValue());
            population.setVillage_population(sheet.getRow(18).getCell(1).getNumericCellValue());
            population.setSource(sheet.getRow(19).getCell(0).getStringCellValue());
            PopulationService.insert(population);
        }*/
        return "s";
    }
    @RequestMapping(value = "/baseinfo_delete")
    @ResponseBody
    public String baseinfo_delete(String country_code){
        Boolean judge=null;
        try{
            judge=NationInfoService.delete(country_code);
        }catch (Exception e){
            e.printStackTrace();
            return "删除失败";
        }
        if(judge)
            return "删除成功";
        else
            return "删除失败";
    }
}
